package com.shorturl.services;


import com.mongodb.*;
import com.shorturl.beans.UrlModel;
import org.springframework.data.mongodb.core.MongoTemplate;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class UrlService {

    private DBCollection _urls;

    public UrlService(DBCollection _urls) {
        this._urls = _urls;
    }

    public void setMongoTemplate(MongoTemplate mongoTemplate) {
        this._urls = mongoTemplate.getCollection("urls");
    }

    public WriteResult save(UrlModel url){
        DBObject object = new BasicDBObject(4);
        object.put("key", url.getKey());
        object.put("url", url.getUrl());
        object.put("userId", url.getUserId());
        object.put("addTime", url.getAddTime());
        return _urls.save(object);
    }

    public List<UrlModel> getUrls(DBObject where, int page){
        return getUrls(where, page, 10);
    }

    public List<UrlModel> getUrls(int page, int pageSize){
        return getUrls(null, page, pageSize);
    }

    public List<UrlModel> getUrls(int limit){
        return getUrls(null, 1, limit);
    }

    public List<UrlModel> getUrls(DBObject where){
        return getUrls(where, 1, 10);
    }

    public List<UrlModel> getUrls(DBObject where, int page, int pageSize){
        DBCursor cursor = _urls.find(where).limit(pageSize).skip(page * pageSize - pageSize);
        ArrayList<UrlModel> list = new ArrayList<UrlModel>(pageSize);
        while (cursor.hasNext()){
            DBObject row = cursor.next();
            UrlModel model = new UrlModel();
            model.setKey(row.get("key").toString());
            model.setUrl(row.get("url").toString());
            model.setUserId((Integer) row.get("userId"));
            model.setAddTime(new Date(row.get("addTime").toString()));
            list.add(model);
        }
        return list;
    }
}
